﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

// WinForms
using System.Windows.Forms.Integration;
using PlayerTest.Player.Event;
using PlayerTest.Player;
using PlayerTest.Player.Controller;
using System.Diagnostics;
using PlayerTest.CustomControls;
using System.Windows.Threading;

namespace PlayerTest
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {
        public event PlayerEventHandler OnPlayerEvent;
        private System.Windows.Forms.Panel panel;

        private Controller control;
        private double volume = 0.5f;

        // 파일 처리
        String videoPath = null;
        String subtitlePath = null;

        private bool isShow = true;
        private bool recording = false;

        #region 초기화 / 해제

        public MainWindow()
        {
            InitializeComponent();

            // WinForms
            //System.Windows.Forms.Integration.WindowsFormsHost.EnableWindowsFormsInterop();  // Message pump redirection
            System.Windows.Forms.Panel panel = new System.Windows.Forms.Panel();
            panel.MouseDown += new System.Windows.Forms.MouseEventHandler(panel_MouseDown);
            WFHost.Child = panel;

            // Controller 초기화
            control = new Controller(panel);
            control.EventHandler += new ControlEventHandler(OnControlEvent);
        }

        /// <summary>
        /// Player에게 이벤트 전송
        /// </summary>
        /// <param name="arg"></param>
        private void SendPlayerEvent(PlayerEventArgs arg)
        {
            PlayerEventHandler handler = OnPlayerEvent;

            if (handler != null) handler(this, arg);
        }

        void panel_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                WFHost.ContextMenu.IsOpen = true;
            }
        }
        
        private void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            control.Stop();
            control.SaveStudyInfo();
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            IntPtr handle = new System.Windows.Interop.WindowInteropHelper(this).Handle;
            control.SetWindowHandle(handle);
        }

        #endregion

        #region 영상 / 자막 열기
        private void OpenVideoFile(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
            dlg.Filter = "동영상 파일|*.avi;*.mp4|모든 파일|*.*";
            dlg.FilterIndex = 1;
            dlg.RestoreDirectory = true;

            try
            {
                if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    PlayerTitle.Content = dlg.SafeFileName;
                    if (control.Open(dlg.FileName))
                    {
                        PlayButton.Visibility = System.Windows.Visibility.Collapsed;
                        PauseButton.Visibility = System.Windows.Visibility.Visible;

                        // 파일이 오픈되면 자막 파싱 시작
                        ScriptLoadingImage.Visibility = System.Windows.Visibility.Visible;  // 로딩 애니메이션
                        String sub = dlg.FileName.Substring(0, dlg.FileName.LastIndexOf("."));
                        sub += ".smi";
                        System.IO.FileInfo fi_sub = new System.IO.FileInfo(sub);
                        if (fi_sub != null)
                        {
                            System.IO.File.Copy(sub, "temp.smi", true);
                            control.OpenSubtitle(sub);
                        }
                        //Timer.Stop();
                        Timer.Interval = TimeSpan.FromSeconds(1);
                        Timer.Tick += new EventHandler(TimerTick);
                        //Timer.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("동영상을 여는 도중 오류가 발생하였습니다.\n\n" + ex.Message);
            }

        }

        private void OpenSubtitleFile(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
            dlg.Filter = "자막파일|*.smi";
            dlg.FilterIndex = 1;
            dlg.RestoreDirectory = true;

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ScriptLoadingImage.Visibility = System.Windows.Visibility.Visible;
                control.OpenSubtitle(dlg.FileName);
            }
        }
        #endregion

        #region Control 이벤트 처리

        // Control Event 처리
        private void OnControlEvent(object sender, ControlEventArgs arg)
        {
            switch (arg.EventType)
            {
                case ControlEventArgs.eventtype.MAXPOS:
                    PositionSlider.Maximum = arg.IntValue;
                    System.Diagnostics.Trace.WriteLine(string.Format("Max pos : {0}", PositionSlider.Maximum));
                    break;

                case ControlEventArgs.eventtype.CURRENTPOS:
                    PositionSlider.Value = arg.IntValue;
                    break;

                case ControlEventArgs.eventtype.LOGIN:
                    if (arg.Result)
                    {
                        LoginButton.Visibility = System.Windows.Visibility.Hidden;
                        LogoutButton.Visibility = System.Windows.Visibility.Visible;

                        lb_LoginID.Content = arg.Message + "님 로그인";
                        lb_LoginID.Visibility = System.Windows.Visibility.Visible;

                        loginWindow.Visibility = System.Windows.Visibility.Hidden;
                    }
                    else
                    {
                        MessageBox.Show("ID나 비밀번호가 잘못되었습니다.", "로그인 실패");
                        //tb_loginID.Focus();
                    }
                    break;

                case ControlEventArgs.eventtype.ERROR:
                    MessageBox.Show(arg.Message);
                    break;

                case ControlEventArgs.eventtype.UPDATESECTION:
                    // 반복구간 정보 업데이트
                    UpdateSection();
                    UpdateMyNoteSection();
                    break;

                case ControlEventArgs.eventtype.UPDATESCRIPT:
                    // 스크립트 업데이트
                    UpdateScript();
                    break;

                case ControlEventArgs.eventtype.UPDATESTUDYINFO:
                    UpdateSection();
                    
                    // 내 학습정보 업데이트
                    UpdateMyNoteSection();
                    UpdateMyNoteSentence();
                    UpdateMyNoteWord();

                    // 추천 학습정보 업데이트
                    UpdateRecommendSection();
                    UpdateRecommendSentence();
                    UpdateRecommendWord();
                    break;

                case ControlEventArgs.eventtype.SUBOPENERROR:
                    ScriptLoadingImage.Visibility = System.Windows.Visibility.Hidden;
                    MessageBox.Show("자막 파일을 열지 못했습니다!", "오류");
                    break;

                case ControlEventArgs.eventtype.JOIN:
                    if (arg.Result)
                    {
                        MessageBox.Show("회원 가입이 완료되었습니다!");
                        control.Login(tb_joinID.Text, tb_joinPW_1.Password);
                        joinWindow.Visibility = System.Windows.Visibility.Hidden;
                        loginWindow.Visibility = System.Windows.Visibility.Hidden;
                    }
                    else
                    {
                        MessageBox.Show(arg.Message, "오류");
                        //tb_loginID.Focus();
                    }
                    break;
            }
        }

        /// <summary>
        /// 자막을 스크립트로 파싱한 결과를 출력합니다.
        /// </summary>
        private void UpdateScript()
        {
            scriptStackPanel.Children.Clear();

            if (ScriptKorButton.Checked)
            {
                // 한글자막
                for (int i = 0; i < control.KRCCScriptDictionary.Count; i++)
                {
                    ScriptItem item = new ScriptItem();
                    item.eventHandler += new ScriptItemEventHandler(OnScriptItemEvent);
                    string str = control.KRCCScriptDictionary[i].Text;
                    string sub = str.Replace(" ", "");
                    if (sub != "")
                    {
                        item.SMI = control.KRCCScriptDictionary[i];
                        //item.text.Text = str;
                        //item.ID = i;
                        scriptStackPanel.Children.Add(item);
                    }
                }
            }
            else if (ScriptEngButton.Checked)
            {
                // 영문자막
                for (int i = 0; i < control.ENCCScriptDictionary.Count; i++)
                {
                    ScriptItem item = new ScriptItem();
                    item.eventHandler += new ScriptItemEventHandler(OnScriptItemEvent);
                    string str = control.ENCCScriptDictionary[i].Text;
                    string sub = str.Replace(" ", "");
                    if (sub != "")
                    {
                        item.SMI = control.ENCCScriptDictionary[i];
                        //item.text.Text = str;
                        //item.ID = i;
                        scriptStackPanel.Children.Add(item);
                    }
                }
            }
            

            // 통합자막
            // ?????????

            ScriptLoadingImage.Visibility = System.Windows.Visibility.Hidden;
        }

        /// <summary>
        /// 구간정보 업데이트
        /// </summary>
        private void UpdateSection()
        {
            sectionStackPanel.Children.Clear();
            for (int i = 0; i < control.SectionDictionary.Count; i++)
            {
                SectionItem item = new SectionItem();
                item.eventHandler += new SectionItemEventHandler(OnSectionItemEvent);
                item.Start = control.SectionDictionary[i].Start;
                item.End = control.SectionDictionary[i].End;
                item.Thumb = control.SectionDictionary[i].Thumb;

                sectionStackPanel.Children.Add(item);
            }
        }

        /// <summary>
        /// MyNote 구간정보 업데이트
        /// </summary>
        private void UpdateMyNoteSection()
        {
            mynoteSectionStackPanel.Children.Clear();
            for (int i = 0; i < control.SectionDictionary.Count; i++)
            {
                SectionItem item = new SectionItem();
                item.eventHandler += new SectionItemEventHandler(OnSectionItemEvent);
                item.Start = control.SectionDictionary[i].Start;
                item.End = control.SectionDictionary[i].End;
                item.Thumb = control.SectionDictionary[i].Thumb;

                mynoteSectionStackPanel.Children.Add(item);
            }
        }

        /// <summary>
        /// MyNote 단어 업데이트
        /// </summary>
        private void UpdateMyNoteWord()
        {
            mynoteWordStackPanel.Children.Clear();
            for (int i = 0; i < control.WordDictionary .Count; i++)
            {
                WordItem item = new WordItem();
                item.Word = control.WordDictionary[i].Word;

                mynoteWordStackPanel.Children.Add(item);
            }
        }

        /// <summary>
        /// MyNote 문장 업데이트
        /// </summary>
        private void UpdateMyNoteSentence()
        {
            mynoteSentenceStackPanel.Children.Clear();
            for (int i = 0; i < control.SentenceDictionary.Count; i++)
            {
                SentenceItem item = new SentenceItem();
                item.Position = control.SentenceDictionary[i].Start;
                item.Text = control.SentenceDictionary[i].Sent;

                mynoteSentenceStackPanel.Children.Add(item);
            }
        }

        /// <summary>
        /// Recommend 구간정보 업데이트
        /// </summary>
        private void UpdateRecommendSection()
        {
            ShowingSectionStackPanel.Children.Clear();
            for (int i = 0; i < control.RecommendSectionDictionary.Count; i++)
            {
                SectionItem item = new SectionItem();
                item.eventHandler += new SectionItemEventHandler(OnSectionItemEvent);
                item.Start = control.RecommendSectionDictionary[i].Start;
                item.End = control.RecommendSectionDictionary[i].End;
                item.Thumb = control.RecommendSectionDictionary[i].Thumb;

                ShowingSectionStackPanel.Children.Add(item);
            }
        }

        /// <summary>
        /// Recommend 단어 업데이트
        /// </summary>
        private void UpdateRecommendWord()
        {
            ShowingWordStackPanel.Children.Clear();
            for (int i = 0; i < control.RecommendWordDictionary.Count; i++)
            {
                WordItem item = new WordItem();
                item.Word = control.RecommendWordDictionary[i].Word;

                ShowingWordStackPanel.Children.Add(item);
            }
        }

        /// <summary>
        /// Recommend 문장 업데이트
        /// </summary>
        private void UpdateRecommendSentence()
        {
            ShowingSentenceStackPanel.Children.Clear();
            for (int i = 0; i < control.RecommendSentenceDictionary.Count; i++)
            {
                SentenceItem item = new SentenceItem();
                item.Position = control.RecommendSentenceDictionary[i].Start;
                item.Text = control.RecommendSentenceDictionary[i].Sent;

                ShowingSentenceStackPanel.Children.Add(item);
            }
        }


        #endregion

        #region UI 이벤트

        private void Titlebar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void OnCloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void tb_loginPW_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                OnDoLoginButton_Click(this, null);
            }
        }
        /// <summary>
        /// 재생 막대 변경시 이벤트 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnPositionSliderChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            Trace.WriteLine(string.Format("New slider position : {0}", e.NewValue));
            control.SetPosition(e.NewValue);
        }

        /// <summary>
        /// 재생 막대 변경시 이벤트 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnVolumeSliderChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            Trace.WriteLine(string.Format("New Volume slider position : {0}", e.NewValue));
            control.SetVolume(e.NewValue);
            volume = e.NewValue;
        }

        private void OnMouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (e.Delta > 0)
            {
                volume += 0.1f;
                if (volume > 1.0f) volume = 1.0f;
            }
            else if (e.Delta < 0)
            {
                volume -= 0.1f;
                if (volume < 0.0f) volume = 0.0f;
            }
            control.SetVolume(volume);
            VolumeSlider.Value = volume;
        }

        private DispatcherTimer Timer = new DispatcherTimer();
        private void TimerTick(object o, EventArgs e)
        {
            // Time Seekbar 조정
            PositionSlider.Value = control.GetPosition();
        }
        #endregion

        #region Custom Control 이벤트
        // ScriptItem Event 처리
        private void OnScriptItemEvent(object sender, ScriptItemEventArgs arg)
        {
            //UserControl uc = sender as UserControl;
            switch (arg.EventType)
            {
                case ScriptItemEventArgs.eventtype.SENTENCE:
                    control.SentenceDictionary.Add(new Player.Data.InfoSentence((long)arg.Position, arg.Message));
                    UpdateMyNoteSentence();
                    break;

                case ScriptItemEventArgs.eventtype.WORD:
                    control.WordDictionary.Add(new Player.Data.InfoWord(arg.Message));
                    UpdateMyNoteWord();
                    break;
            }
        }

        // Section Item Event 처리
        private void OnSectionItemEvent(object sender, SectionItemEventArgs arg)
        {
            //UserControl uc = sender as UserControl;
            switch (arg.EventType)
            {
                case SectionItemEventArgs.eventtype.REPEAT:
                    // 구간반복 개선 필요
                    control.Repeat(arg.Start, arg.End);
                    break;

                case SectionItemEventArgs.eventtype.RECORDSTART:
                    control.RecordStart();
                    break;

                case SectionItemEventArgs.eventtype.RECORDEND:
                    control.RecordEnd();
                    break;
            }
        }

        #endregion

        #region UI 버튼 실행

        // 세밀한 재생 컨트롤??
        private void OnThumbnailTest(object sender, RoutedEventArgs e)
        {
            if (isShow)
            {
                // 숨기기
                //image1.SetValue(Image.MarginProperty, new Thickness(0, 0, 0, 0));
                isShow = false;
                //image1.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                // 표시하기
                //image1.SetValue(Image.MarginProperty, new Thickness(250,0,0,43));
                isShow = true;
                //image1.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void OnJoinPageButton_Click(object sender, RoutedEventArgs e)
        {
            joinWindow.Visibility = System.Windows.Visibility.Visible;
        }
        private void OnJoinPageCloseButton_Click(object sender, RoutedEventArgs e)
        {
            joinWindow.Visibility = System.Windows.Visibility.Hidden;
        }
        private void OnLoginPageCloseButton_Click(object sender, RoutedEventArgs e)
        {
            loginWindow.Visibility = System.Windows.Visibility.Hidden;
        }

        private void OnDoJoinButton_Click(object sender, RoutedEventArgs e)
        {
            if (tb_joinID.Text.Length != 0 && tb_joinName.Text.Length != 0 &&
                tb_joinPW_1.Password.Length != 0 && tb_joinPW_2.Password == tb_joinPW_1.Password)
                control.Join( tb_joinID.Text, tb_joinName.Text, tb_joinPW_1.Password );
            else
            {
                MessageBox.Show("가입 정보가 잘못되었습니다!");
            }

        }

        private void OnTabItem_Click(object sender, RoutedEventArgs e)
        {
            UserControl tab = sender as UserControl;
            switch (tab.Name)
            {
                case "ViewingTabItem":
                    TabSelect("Viewing");
                    break;

                case "RecordingTabItem":
                    TabSelect("Recording");
                    break;

                case "ShowingTabItem":
                    TabSelect("Showing");
                    break;

                case "MyNoteTabItem":
                    TabSelect("MyNote");
                    break;
            }

        }

        private void OnUploadButton_Click(object sender, RoutedEventArgs e)
        {
            TabSelect("Showing");
            //webBrowser1.Source = new Uri("http://winz.myvnc.com/sub/Controller/Upload/uploadpage.jsp");
        }

        private void TabSelect(string tab)
        {
            ViewingTabItem.Checked = false;
            RecordingTabItem.Checked = false;
            ShowingTabItem.Checked = false;
            MyNoteTabItem.Checked = false;

            Grid_Viewing.Visibility = System.Windows.Visibility.Hidden;
            Grid_Recording.Visibility = System.Windows.Visibility.Hidden;
            Grid_Showing.Visibility = System.Windows.Visibility.Hidden;
            Grid_MyNote.Visibility = System.Windows.Visibility.Hidden;

            switch (tab)
            {
                case "Viewing":
                    ViewingTabItem.Checked = true;
                    Grid_Viewing.Visibility = System.Windows.Visibility.Visible;
                    break;

                case "Recording":
                    RecordingTabItem.Checked = true;
                    Grid_Recording.Visibility = System.Windows.Visibility.Visible;
                    break;

                case "Showing":
                    ShowingTabItem.Checked = true;
                    Grid_Showing.Visibility = System.Windows.Visibility.Visible;
                    break;

                case "MyNote":
                    MyNoteTabItem.Checked = true;
                    Grid_MyNote.Visibility = System.Windows.Visibility.Visible;
                    break;
            }
        }

        private void OnMyNote_Menu(object sender, RoutedEventArgs e)
        {
            UserControl noteMenu = sender as UserControl;
            switch (noteMenu.Name)
            {
                case "MyNote_SectionButton":
                    MyNoteMenuSelect("Section");
                    break;

                case "MyNote_WordButton":
                    MyNoteMenuSelect("Word");
                    break;

                case "MyNote_SentenceButton":
                    MyNoteMenuSelect("Sentence");
                    break;
            }
        }

        private void MyNoteMenuSelect(string tab)
        {
            MyNote_SectionButton.Checked = false;
            MyNote_WordButton.Checked = false;
            MyNote_SentenceButton.Checked = false;

            mynoteSectionScrollPanel.Visibility = System.Windows.Visibility.Hidden;
            mynoteWordScrollPanel.Visibility = System.Windows.Visibility.Hidden;
            mynoteSentenceScrollPanel.Visibility = System.Windows.Visibility.Hidden;

            switch (tab)
            {
                case "Section":
                    MyNote_SectionButton.Checked = true;
                    mynoteSectionScrollPanel.Visibility = System.Windows.Visibility.Visible;
                    break;

                case "Word":
                    MyNote_WordButton.Checked = true;
                    mynoteWordScrollPanel.Visibility = System.Windows.Visibility.Visible;
                    break;

                case "Sentence":
                    MyNote_SentenceButton.Checked = true;
                    mynoteSentenceScrollPanel.Visibility = System.Windows.Visibility.Visible;
                    break;
            }
        }

        private void OnShowing_Menu(object sender, RoutedEventArgs e)
        {
            UserControl showingMenu = sender as UserControl;
            switch (showingMenu.Name)
            {
                case "Showing_SectionButton":
                    ShowingMenuSelect("Section");
                    break;

                case "Showing_WordButton":
                    ShowingMenuSelect("Word");
                    break;

                case "Showing_SentenceButton":
                    ShowingMenuSelect("Sentence");
                    break;
            }
        }

        private void ShowingMenuSelect(string tab)
        {
            Showing_SectionButton.Checked = false;
            Showing_WordButton.Checked = false;
            Showing_SentenceButton.Checked = false;

            ShowingSectionScrollPanel.Visibility = System.Windows.Visibility.Hidden;
            ShowingWordScrollPanel.Visibility = System.Windows.Visibility.Hidden;
            ShowingSentenceScrollPanel.Visibility = System.Windows.Visibility.Hidden;

            switch (tab)
            {
                case "Section":
                    Showing_SectionButton.Checked = true;
                    ShowingSectionScrollPanel.Visibility = System.Windows.Visibility.Visible;
                    break;

                case "Word":
                    Showing_WordButton.Checked = true;
                    ShowingWordScrollPanel.Visibility = System.Windows.Visibility.Visible;
                    break;

                case "Sentence":
                    Showing_SentenceButton.Checked = true;
                    ShowingSentenceScrollPanel.Visibility = System.Windows.Visibility.Visible;
                    break;
            }
        }
        

        private void ImageButtonControl_Click(object sender, EventArgs e)
        {
            MessageBox.Show("클릭!");
        }

        private void OnLoginButton_Click(object sender, RoutedEventArgs e)
        {
            if (loginWindow.Visibility == System.Windows.Visibility.Hidden)
            {
                loginWindow.Visibility = System.Windows.Visibility.Visible;
                tb_loginID.Focus();
            }
            else
            {
                loginWindow.Visibility = System.Windows.Visibility.Hidden;
            }
            //control.Login("user", "12345");
        }

        private void OnDoLoginButton_Click(object sender, RoutedEventArgs e)
        {
            if (tb_loginID.Text != "" && tb_loginPW.Password != "")
            {
                control.Login(tb_loginID.Text, tb_loginPW.Password);
            }
            else
            {
                MessageBox.Show("ID와 비밀번호를 입력해 주세요!");
                tb_loginID.Focus();
            }
        }

        private void OnLogoutButton_Click(object sender, RoutedEventArgs e)
        {
            // 학습정보 있다면 저장
            control.SaveStudyInfo();

            lb_LoginID.Visibility = System.Windows.Visibility.Hidden;
            LoginButton.Visibility = System.Windows.Visibility.Visible;
            LogoutButton.Visibility = System.Windows.Visibility.Hidden;
            control.Logout();

        }

        private void OnCaptureButton_Click(object sender, RoutedEventArgs e)
        {
            control.Capture();
        }

        private void OnSpeed_Changed(object sender, RoutedEventArgs e)
        {
            UserControl speed = sender as UserControl;
            switch (speed.Name)
            {
                case "SpeedButton_10":
                    SpeedButton_10.Checked = true;
                    break;
            }
        }
        private void OnPlayButton_Click(object sender, RoutedEventArgs e)
        {
            if (control.Opened)
            {
                control.Play();
                PlayButton.Visibility = System.Windows.Visibility.Collapsed;
                PauseButton.Visibility = System.Windows.Visibility.Visible;
            }
            else
                OpenVideoFile(sender, e);
        }
        private void OnPauseButton_Click(object sender, RoutedEventArgs e)
        {
            control.Pause();
            PlayButton.Visibility = System.Windows.Visibility.Visible;
            PauseButton.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void OnStopButton_Click(object sender, RoutedEventArgs e)
        {
            control.Stop();
        }
        private void OnRecordButton_Click(object sender, RoutedEventArgs e)
        {
            if (!recording)
            {
                control.RecordStart();
                recording = true;
            }
            else
            {
                control.RecordEnd();
                recording = false;
            }
        }
        private void onWindowSizeChanged(object sender, SizeChangedEventArgs e)
        {
            control.Resize();
        }
        private void OnPrevPositionButton_Click(object sender, RoutedEventArgs e)
        {

        }
        private void OnNextPositionButton_Click(object sender, RoutedEventArgs e)
        {

        }
        private void OnSubtitleChange_Click(object sender, RoutedEventArgs e)
        {
            UserControl sub = sender as UserControl;
            SubEngButton.Checked = false;
            SubKorButton.Checked = false;
            SubNoneButton.Checked = false;
            SubUnitedButton.Checked = false;

            switch (sub.Name)
            {
                case "SubUnitedButton":
                    SubUnitedButton.Checked = true;
                    control.SubtitleType = CorePlayer.SubType.UNITED;
                    break;

                case "SubKorButton":
                    SubKorButton.Checked = true;
                    control.SubtitleType = CorePlayer.SubType.KRCC;
                    break;

                case "SubEngButton":
                    SubEngButton.Checked = true;
                    control.SubtitleType = CorePlayer.SubType.ENCC;
                    break;

                case "SubNoneButton":
                    SubNoneButton.Checked = true;
                    control.SubtitleType = CorePlayer.SubType.NONE;
                    break;
            }
        }
        private void OnScriptChange_Click(object sender, RoutedEventArgs e)
        {
            UserControl script = sender as UserControl;
            ScriptEngButton.Checked = false;
            ScriptKorButton.Checked = false;
            //ScriptUnitedButton.Checked = false;

            switch (script.Name)
            {
                case "ScriptUnitedButton":
                    //ScriptUnitedButton.Checked = true;
                    break;

                case "ScriptKorButton":
                    ScriptKorButton.Checked = true;
                    break;

                case "ScriptEngButton":
                    ScriptEngButton.Checked = true;
                    break;
            }
            UpdateScript();
        }
        
        private void OnRepeatSection_Start(object sender, RoutedEventArgs e)
        {
            string str = string.Format("[구간 시작] : {0}", control.SectionStart());
            PlayerMessage.Content = str;
        }
        private void OnRepeatSection_End(object sender, RoutedEventArgs e)
        {
            string str = string.Format("[구간 종료] : {0}", control.SectionEnd());
            PlayerMessage.Content = str;
        }
        private void OnRepeatSection_Release(object sender, RoutedEventArgs e)
        {
            PlayerMessage.Content = "구간 반복 해제";
            control.SectionRelease();
        }
        
        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            Trace.WriteLine(string.Format("[KEY] {0}", e.Key));
            String str;
            switch (e.Key)
            {
                case Key.Space:
                    control.Pause();
                    break;

                // 구간반복 시작
                // [ 키
                case Key.OemOpenBrackets:
                    str = control.SectionStart();
                    PlayerMessage.Content = str;
                    break;

                // ] 키
                case Key.Oem6:
                    str = control.SectionEnd();
                    PlayerMessage.Content = str;
                    break;
            }
        }
        private void MinimumButton_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void MaximumButton_Click(object sender, RoutedEventArgs e)
        {
            //this.WindowState = WindowState.Maximized;
        }
        #endregion

    }
}